#!/bin/bash

# 检查是否以 root 用户运行
if [ "$(id -u)" -ne 0 ]; then
    echo "此脚本必须以 root 用户运行" 1>&2
    exit 1
fi

# 获取当前版本信息
CURRENT_DIR=$(pwd)
CURRENT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "未知")
echo "当前版本: $CURRENT_COMMIT"

# 拉取最新代码
echo "从远程仓库拉取最新代码..."
git fetch
if [ $? -ne 0 ]; then
    echo "拉取代码失败，请检查网络连接和仓库配置" 1>&2
    exit 1
fi

# 检查是否有更新
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})

if [ "$LOCAL" = "$REMOTE" ]; then
    echo "已经是最新版本，无需升级"
    exit 0
fi

# 更新代码
echo "更新代码到最新版本..."
git pull
if [ $? -ne 0 ]; then
    echo "更新代码失败，可能存在冲突" 1>&2
    exit 1
fi

# 显示新版本信息
NEW_COMMIT=$(git rev-parse --short HEAD)
echo "新版本: $NEW_COMMIT"
echo "更新日志:"
git log --oneline $CURRENT_COMMIT..$NEW_COMMIT

# 备份当前配置
echo "备份当前配置..."
BACKUP_DIR="/usr/local/etc/2rtk.backup.$(date +%Y%m%d%H%M%S)"
mkdir -p $BACKUP_DIR
if [ $? -ne 0 ]; then
    echo "创建备份目录失败" 1>&2
    exit 1
fi

cp -a /usr/local/etc/2rtk/* $BACKUP_DIR/
if [ $? -ne 0 ]; then
    echo "备份配置文件失败" 1>&2
    exit 1
fi
echo "配置已备份到 $BACKUP_DIR"

# 停止服务
echo "停止 2RTK Caster 服务..."
systemctl stop 2rtk-caster.service

# 编译新版本
echo "编译新版本..."
cd caster
make clean
make
if [ $? -ne 0 ]; then
    echo "编译失败，恢复服务..." 1>&2
    systemctl start 2rtk-caster.service
    exit 1
fi

# 检查编译后的二进制文件是否存在
if [ ! -f bin/caster ]; then
    echo "编译后的二进制文件不存在" 1>&2
    systemctl start 2rtk-caster.service
    exit 1
fi

# 安装新版本
echo "安装新版本..."
install -m 755 bin/caster /usr/local/sbin/
if [ $? -ne 0 ]; then
    echo "安装二进制文件失败" 1>&2
    systemctl start 2rtk-caster.service
    exit 1
fi

# 启动服务
echo "启动 2RTK Caster 服务..."
systemctl start 2rtk-caster.service

# 检查服务状态
echo "检查服务状态..."
systemctl status 2rtk-caster.service --no-pager

echo "升级完成！从 $CURRENT_COMMIT 升级到 $NEW_COMMIT"
echo "如果需要恢复之前的配置，请运行："
echo "cp -a $BACKUP_DIR/* /usr/local/etc/2rtk/"
echo "systemctl restart 2rtk-caster.service"